﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace HobSoft.SoccerBet2014.Domain.Common.Site
{            
    using SiteContext;
    using Domain.DataService;
    using Domain.Models;
    using Component;

    public class HgSessionManager : SessionManagerBase
    {

        public HgSessionManager(ICookiesManager cookieManager, IBetGameDataService repository, string globalHost, byte bookerId, string account)
            : base(cookieManager, repository, globalHost, bookerId, account)
        {
        }
        public string SessionUID { get; protected set; }
        public string SessionLiveID { get; protected set; }
        public string SessionCasiNo { get; protected set; }

        protected string HtmlLoginForm { get; set; }

        public override async Task<bool> Start()
        {
            if (!ValidInitialize())
                return false;

            Uri url = new Uri(string.Format("http://{0}/app/member/", GlobalHost));
            string referer = string.Format("http://{0}/", GlobalHost);
            HttpWebRequest request = CreateRequest(url, null, HTML_MIME, null, null, "GET");
            var resTask = request.GetResponseAsync();
            HttpWebResponse response = (HttpWebResponse)await resTask;
            if (response.Cookies != null)
            {
                foreach (Cookie cookie in response.Cookies)
                {
                    CookiesManager.SetCookies(BookerID, Account, cookie);
                }
            }

            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream, Encoding);
            HtmlLoginForm = reader.ReadToEnd();
            resStream.Close();
            response.Close();
            Debug.WriteLine("==========登录准备完毕，请求结果如下===========");
            Debug.WriteLine(HtmlLoginForm);
            if (string.IsNullOrEmpty(HtmlLoginForm))
                return false;
            //DebugResponseResult(response);
            //DebugResponseCookies(response);
            return true;
        }

        public override async Task<bool> Signup(string password, string token)
        {
            if (!ValidInitialize() && string.IsNullOrEmpty(HtmlLoginForm))
                return false;

            Uri url = new Uri(string.Format("http://{0}/app/member/login.php", GlobalHost));
            string referer = string.Format("http://{0}/app/member/", GlobalHost);
            string content = string.Empty;
            try
            {
                HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(HtmlLoginForm);
                var loginForm = htmlDoc.DocumentNode.SelectSingleNode("//form[@name='LoginForm']");
                var formNodes = loginForm.SelectNodes("//input");
                HtmlFormHelper formHelper = new HtmlFormHelper(formNodes);

                formHelper.ChangeValueByName("username", Account);
                formHelper.ChangeValueByName("passwd", password);

                content = formHelper.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("创建用户登录提交发生异常", ex);
            }

            try
            {
                var cookies = CookiesManager.GetCookies(BookerID, Account, url);
                var request = CreateRequest(url, cookies, HTML_MIME, referer, content, "POST");
                request.ContentType = "application/x-www-form-urlencoded";
                var resTask = request.GetResponseAsync();
                HttpWebResponse response = (HttpWebResponse)await resTask;
                Stream resStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(resStream, Encoding);
                var result = reader.ReadToEnd();
                resStream.Close();
                response.Close();
                //DebugResponseResult(response);

                Regex regUid = new Regex(@"(?:top\.uid(\s?)=(\s?)'(?<v>[\w]+)'[\n|;])", RegexOptions.Compiled);
                Regex regLvid = new Regex(@"(?:top\.liveid(\s?)=(\s?)'(?<v>[\w]+)'[\n|;])", RegexOptions.Compiled);
                Regex regcasino = new Regex(@"(?:top\.casino(\s?)=(\s?)'(?<v>[\w]+)'[\n|;])", RegexOptions.Compiled);
                Regex regError = new Regex(@"(?:alert\s*\(\s*'(?<m>[^']+)'\s*\)\s*[\n|;])", RegexOptions.Compiled);
                var matUid = regUid.Match(result);
                var matLvid = regLvid.Match(result);
                var matCasino = regcasino.Match(result);
                Debug.WriteLine("==========登录请求完成===========");
                if (matUid.Success)
                {
                    SessionUID = matUid.Groups["v"].Value;
                    SessionLiveID = matLvid.Groups["v"].Value;
                    SessionCasiNo = matCasino.Groups["v"].Value;
                    Host = GlobalHost;
                }
                else
                {
                    var matError = regError.Match(result);
                    if (matError.Success)
                    {
                        Debug.WriteLine(matError.Groups["m"].Value);
                    }
                    return false;
                }
                Debug.WriteLine("UID:{0}/LiveID:{1}/CasiNo:{2}", SessionUID, SessionLiveID, SessionCasiNo);
                //DebugResponseCookies(response);
                /*
                 * <script>
                    top.uid = '4770f14em10957350l80390920';
                    top.langx = 'zh-cn';
                    top.liveid = 'c8cac6cfcec298cacfcacc'
                    top.casino = 'SI2';
                    top.hot_game = '';
                    top.hasLogin = 'login';
                    </script>
                 */
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }

        public override Task RequestSignupToken()
        {
            throw new NotImplementedException();
        }

        public override Task ChangeLauguage()
        {
            throw new NotImplementedException();
        }

        public async override Task StartHeartbeat()
        {
            throw new NotImplementedException();
        }

        public override async Task<string> RequestMainPage()
        {
            Uri url = new Uri(string.Format("http://{0}/app/member/FT_browse/body_var.php?uid={1}&rtype=r&langx=zh-cn&mtype=4&delay=&league_id=&hot_game=", Host, SessionUID));
            string referer = string.Format("http://{0}/app/member/FT_browse/index.php?uid={1}&langx=zh-cn&mtype=4&league_id=&showtype=", Host, SessionUID);
            var reqTask = GetHtmlRequest(url, null, "");
            return await reqTask;
        }

        protected override bool CheckLoginHtmlState(string html)
        {
            throw new NotImplementedException();
        }

        public override Task<IList<Game>> RequestEarlyMarketOdds()
        {
            throw new NotImplementedException();
        }

        protected override string SessionID
        {
            get { throw new NotImplementedException(); }
        }

        protected override bool ValidHostIsWWW(string host)
        {
            throw new NotImplementedException();
        }

        protected override string WWWHost()
        {
            throw new NotImplementedException();
        }

        public override Task<bool> RequestUpdateLiveOdds()
        {
            throw new NotImplementedException();
        }

        public override Task<bool> RequestUpdateTodayOdds()
        {
            throw new NotImplementedException();
        }

        public override Task<IList<Game>> RequestLiveFullOdds()
        {
            throw new NotImplementedException();
        }

        public override Task<IList<Game>> RequestTodayFullOdds()
        {
            throw new NotImplementedException();
        }

        public override Task<bool> CheckSession()
        {
            throw new NotImplementedException();
        }

        public override Task<BetTick> RequestTick(BetTick oldTick)
        {
            throw new NotImplementedException();
        }

        public override Task<BetTick> RequestTick(string oddsId, OddsPrice price)
        {
            throw new NotImplementedException();
        }

        public override Task<bool> Signout()
        {
            throw new NotImplementedException();
        }


        public override Task<Models.Site.BettingResult> RequestBetting(BetTick tick, decimal money)
        {
            throw new NotImplementedException();
        }

        public override Task<IList<Models.Site.BettingOrder>> RequestBettingMiniOrder()
        {
            throw new NotImplementedException();
        }

        public override Task<IList<Models.Site.BettingOrder>> RequestBettingHisOrder()
        {
            throw new NotImplementedException();
        }
    }
}
